package com.kun.admin.controller;

import java.util.Arrays;
import java.util.Map;


import com.kun.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.kun.admin.entity.AdminEntity;
import com.kun.admin.service.AdminService;
import com.kun.common.utils.PageUtils;
import com.kun.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author kun_er
 * @email 2661038743@qq.com
 * @date 2022-05-02 14:53:32
 */
@RestController
@RequestMapping("admin/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Value("${name}")
    String name;
    @GetMapping("/name")
    public String getName(){
        return name;
    }

    /**
     * 登陆
     */
    @PostMapping("/login")
    public R login(@RequestBody AdminEntity admin){
        String res= adminService.login(admin);
        System.out.println(res);
        if (res==null){
            return R.error().put("msg","用户名密码错误");
        }else {
            return R.ok().put("token",res);
        }
    }
    @GetMapping("getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        String id = JwtUtils.getMemberIdByJwtToken(request);
        AdminEntity admin = adminService.getById(id);
        return R.ok().put("data",admin);

    }
    /**
     * 列表
     */
    @RequestMapping("/list")

    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = adminService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")

    public R info(@PathVariable("id") Integer id){
		AdminEntity admin = adminService.getById(id);

        return R.ok().put("admin", admin);
    }

    /**
     *  添加
     */
    @RequestMapping("/save")

    public R save(@RequestBody AdminEntity admin){
        boolean regist = adminService.regist(admin);
        if (regist){
            return R.ok().put("msg","添加成功");
        }else {
            return R.error().put("msg","用户已存在");
        }


    }

    /**
     * 修改
     */
    @RequestMapping("/update")

    public R update(@RequestBody AdminEntity admin){
        boolean b = adminService.updateAdmin(admin);
        if (b){
            return R.ok().put("msg","修改成功");
        }else {
            return R.error().put("msg","修改失败,名字已被占用");
        }

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")

    public R delete(@RequestBody Integer[] ids){
		adminService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
